﻿/******************************************************************************
* File description: ChromatogramManager.cpp
* Function: 提供能谱图功能管理
* Current Version: 1.0.0
* Author: JNN
* Date: 2025-07-01
*  -----
*  Copyright by 博坤生物 .
 *****************************************************************************/


#include "ChromatogramManager.h"

extern int npwhfl;

/** @brief 构造函数 */
ChromatogramManager::ChromatogramManager(){
    _timer_tick = new QTimer(this);
//    _timer_collect = new QTimer(this);
    connect(_timer_tick, SIGNAL(timeout()), this, SLOT(tickOneSecond()));
//    connect(_timer_collect, SIGNAL(timeout()), this, SLOT(onCollectStop()));
}


/** @brief 实验启动时，初始化能谱图 */
void ChromatogramManager::onStartExperiment(){
    onEndExperiment();      // 顺手执行一下endExp的处理，防止奇怪的事情发生
    _timer_tick->start(1000);
    _chart->clear();
    _chart->setFixedMaxX(1000);
//    _chart->setFixedMaxY(800);
}

void ChromatogramManager::tickOneSecond(){

    double value = 0;
    if(_cpsDataList.size() > 0){
        for(int i = 0; i < _cpsDataList.size(); i ++){
            value += _cpsDataList[i];
        }
        value /= _cpsDataList.size();
    }else{
        value = -100;
    }
    _cpsDataList.clear();

    _pointList_raw.append(QPointF(_pointList_raw.size(), value));
    _pointList_filter.append(QPointF(_pointList_filter.size(), value));

    if(_pointList_simp.size() == 0){
        _pointList_simp.append(QPointF(0, value));
    }


    int lastIdx = _pointList_raw.size()-1;
    // 对前几个数据做滤波
    if(lastIdx > 10 && _pointList_filter.size() > lastIdx){
        double coef = 1.0 / 3.0;
        _pointList_filter[lastIdx-2].setY(_pointList_raw[lastIdx-1].y()*coef + _pointList_raw[lastIdx-2].y()*coef + _pointList_raw[lastIdx-3].y()*coef);
    }

//    // 生成简化版曲线: 每10个值取前面的平均值
//    if(_pointList_filter.size() % 10 == 0 && _pointList_filter.size() >= 10){     // 点个数到达10的整数倍
//        double avg = 0;
//        for(int i = _pointList_filter.size()-1; i >= _pointList_filter.size() - 10; i --){
//            avg += _pointList_filter[i].y();
//        }
//        _pointList_simp.append(QPointF(_pointList_filter.size()-1, avg/10.0));      // 每个9的位置有取值
//    }

    QVector<QPointF> lastPointList = _pointList_filter.mid(std::floor(_pointList_filter.size()/10)*10 + 1);

    _chart->setFixedMaxX(std::max(_initMaxX, std::ceil(_pointList_raw.size()/60.0)*60));
    _chart->clear();
    _chart->appendCurve("test", QVector<QPointF>{QPointF(-10, 800)}, QColor(0, 0, 0), 1);        // 用来控制图的最高点至少为800
//    _chart->appendCurve("1raw", _pointList_raw, QColor(211, 233, 255), 2, CustomChart::LINE);
    _chart->appendCurve("2filter", _pointList_filter, QColor(233, 133, 12), 2, CustomChart::LINE);
//    _chart->appendCurve("3filter", _pointList_simp+lastPointList, QColor(233, 133, 12), 2, CustomChart::LINE);


    // 最后一个点加标注
    QPointF lastPoint = _pointList_filter.back();
    _chart->appendCurve("finalPoint", QVector<QPointF>({lastPoint}), QColor(233, 133, 12), 5, CustomChart::SCATTER, CustomChart::RING);
    QVector<QPointF> dotToXAxis, dotToYAxis;
    dotToXAxis.append(QPointF(lastPoint.x(), 0));   dotToXAxis.append(lastPoint);
    dotToYAxis.append(QPointF(0, lastPoint.y()));   dotToYAxis.append(lastPoint);

    _chart->appendCurve("dotToXAxis", dotToXAxis, QColor(200, 200, 200), 1, CustomChart::LINE, CustomChart::DOTTED);
    _chart->appendCurve("dotToYAxis", dotToYAxis, QColor(200, 200, 200), 1, CustomChart::LINE, CustomChart::DOTTED);

    _chart->refresh();
}

///** @brief 停止收集 (已弃用) */
//void ChromatogramManager::onCollectStop(){
//    QTimer::singleShot(_delayTimeStop*1000, [=](){
//        emit sigEndCollect();
//        _timer_collect->stop();
//    });
//}


///** @brief 设置能谱图模式 (已弃用) */
//void ChromatogramManager::setDetectMode(int isAuto, int autoType, int thr, int delayTimeCollect, int timeCollect, int delayTimeStop){
//    _isAuto = isAuto;
//    _autoType = autoType;
//    _threshold = thr;
//    _delayTimeCollect = delayTimeCollect;
//    _timeCollect = timeCollect;
//    _delayTimeStop = delayTimeStop;
//}

///** @brief 设置能谱图模式 (已弃用) */
//void ChromatogramManager::setDetectMode(int isAuto){
//    _isAuto = isAuto;
//}


///** @brief 设置能谱图的阈值线 (已弃用) */
//void ChromatogramManager::setThreshold(int thr){
//    qDebug() << "阈值线变更为" << thr;
//    _threshold = thr;
//}

///** @brief 获取能谱图检测模式 (已弃用) */
//QVariantMap ChromatogramManager::getDetectMode(){
//    QVariantMap res;
//    res["IsAuto"] = _isAuto;
//    res["AutoType"] = _autoType;
//    res["Threshold"] = _threshold;
//    res["DelayTimeCollect"] = _delayTimeCollect;
//    res["TimeCollect"] = _timeCollect;
//    res["DelayTimeStop"] = _delayTimeStop;
//    return res;
//}


///** @brief 判断是否需要收集 (已弃用) */
//void ChromatogramManager::judgeCollectState(){

//    if(_hasCollect){
//        if(_autoType == 2){
//            if(judgeCollectCloseStateByThr()){
//                onCollectStop();
//            }
//        }else{
//            return;
//        }
//    }
//    // 阈值
//    if(_autoType == 0){
//        if(judgeCollectStateByThr()){
//            emit sigStartCollect();
//            _hasCollect = true;
//            _timer_collect->start(_timeCollect*1000);
//        }
//    }else if(_autoType == 1){
//        if(judgeCollectStateByPeak()){
//            qDebug() << "判断Peak返回true";
//            emit sigStartCollect();
//            _hasCollect = true;
//            _timer_collect->start(_timeCollect*1000);
//        }
//    }else if(_autoType == 2){
//        if(judgeCollectStateByThr()){

//            emit sigStartCollect();
//            _hasCollect = true;
//        }
//    }

//}

///** @brief 判断是否需要收集 (已弃用) */
//bool ChromatogramManager::judgeCollectStateByPeak(){
//    qDebug() << "判断Peak" << "HasRise" << _hasRise;
//    // 判断条件: (1)存在上升期 (2)当前阶段斜率达到0
//    double riseSlopeThr = 3;
//    double planeSlopeThr = 0.5;
//    int N = 15;
//    double k, b;
//    if(_cpsPointList_filter.size() < N){
//        return false;
//    }
//    Algorithm::linearFitting(_pointList_raw_filter.mid(std::max(0, _pointList_raw_filter.size()-N), N), &k, &b);
//    qDebug() << "当前斜率" << k;

//    // 上升期判断
//    if(!_hasRise){
//        if(k > riseSlopeThr){
//            _hasRise = true;
//        }
//        return false;
//    }
//    // 判断是否到平滑期
//    else{
//        if(k < planeSlopeThr){
//            return true;
//        }
//        return false;
//    }

//}

///** @brief 判断是否需要收集 (已弃用) */
//bool ChromatogramManager::judgeCollectStateByThr(){
//    // 判断条件: 持续N个点的值大于阈值线
//    int N = 5;
//    for(int i = _pointList_raw_filter.size() - 1; i >= std::max(_pointList_raw_filter.size() - N, 0); i --){
//        if(_pointList_raw_filter[i].y() < _threshold){
//            return false;
//        }
//    }
//    return true;
//}

///** @brief 阈值 (已弃用) */
//bool ChromatogramManager::judgeCollectCloseStateByThr(){
//    // 判断条件: 持续N个点的值小于阈值线
//    int N = 5;
//    for(int i = _pointList_raw_filter.size() - 1; i >= std::max(_pointList_raw_filter.size() - N, 0); i --){
//        if(_pointList_raw_filter[i].y() < _threshold){
//            return false;
//        }
//    }
//    return true;
//}

///** @brief 实验结束触发 */
void ChromatogramManager::onEndExperiment(){
    _timer_tick->stop();
//    _timer_collect->stop();
//    _hasRise = false;
//    _hasCollect = false;
    _pointList_raw.clear();
    _pointList_filter.clear();
    _pointList_simp.clear();
}


///** @brief 刷新图表 */
//void ChromatogramManager::refresh(){

//    refreshPointList();
////    judgeCollectState();

//}


///** @brief 刷新每秒的数据 */
//void ChromatogramManager::refreshPointList(){



////      // 嗯，编数据吧
////      for(int i = 0; i < 1; i ++){
////          int x = _pointList_raw.length();
////          _pointList_raw.append(QPointF(x, 10 + qrand()%10 + 500/(1+pow(2.7, (500.0-x)/20.0))));
////      }

////    // 从设备获取数据
////    QVector<double> dataList = _msgInterface->getCPSData();
////    double value = 0;
////    for(int i = 0; i < dataList.size(); ++i){     // 对发过来的数据取平均作为单个点的数据
////        value += dataList[i];
////    }if(dataList.size()!=0){
////        value /= dataList.size();
////    }else{
////        value = -10000;
////    }
//////    qDebug() << "CPSDataNum:" << dataList.size() << "AvgValue:" << value;
////    _pointList_raw.append(QPointF(_pointList_raw.size(), value));

//    _chart->setFixedMaxX(std::max(_initMaxX, std::ceil(_pointList_raw.size()/60.0)*60));
////    _pointList_raw_filter = Algorithm::filter(_pointList_raw);      // 滤波后数据
//    _chart->clear();
////    _chart->appendCurve("1raw", _pointList_raw, QColor(188, 210, 233, 100), 2);



//    _chart->appendCurve("test", QVector<QPointF>{QPointF(-1, 800)}, QColor(0, 0, 0), 1);
//    _chart->appendCurve("2filter", _pointList_raw, QColor(233, 133, 12), 2, CustomChart::LINE);
//    _chart->refresh();
//}

void ChromatogramManager::appendNewPoint(double value){
    _cpsDataList.append(value);
}


/** @brief 清空图表（不清数据） */
void ChromatogramManager::clearChart(){
    _chart->clear();
    _chart->clearFixedRange();
    _chart->setFixedMaxX(_initMaxX);
    _chart->setFixedMinY(0);
    _chart->setFixedMinX(0);
    _chart->appendCurve("test", QVector<QPointF>{QPointF(-10, 800)}, QColor(0, 0, 0), 1);
    _chart->initShowRange();
    _chart->refresh();
}

/** @breif 包含清除数据和清除图表*/
void ChromatogramManager::clearData(){

    _pointList_raw.clear();
    _pointList_filter.clear();
    _pointList_simp.clear();
    clearChart();
}

/** @brief 根据x坐标获取y坐标*/
double ChromatogramManager::getYByX(double doubleX){

    int x1 = std::floor(doubleX/10);
    int x2 = std::ceil(doubleX/10);

    if(_pointList_simp.size() <= x1){
        return -1;
    }else if(_pointList_simp.size() <= x2){
        double res = _pointList_simp[x1].y() * (doubleX/10.0-x1) + _pointList_simp.back().y() * (x2-doubleX/10.0);
        return res;
    }
    else {
        double res = _pointList_simp[x1].y() * (doubleX/10.0-x1) + _pointList_simp[x2].y() * (x2-doubleX/10.0);
        return res;
    }


}

/** @brief 能谱维护开*/
void ChromatogramManager::opennpwh(){
    npwhfl=1;
}
/** @brief 能谱维护关*/
void ChromatogramManager::closenpwh(){
    npwhfl=0;
}

